package me.zhengjie.modules.inspection.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.inspection.domain.InspectionPlan;
import me.zhengjie.modules.inspection.service.InspectionPlanService;
import me.zhengjie.modules.inspection.service.dto.InspectionPlanDTO;
import me.zhengjie.modules.inspection.service.dto.InspectionPlanQueryCriteria;
import me.zhengjie.modules.security.config.SecurityConfig;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;


/**
* @author xuyukun
* @date 2019-07-21
*/
@RestController
@RequestMapping("api")
public class InspectionPlanController {

    @Autowired
    private InspectionPlanService inspectionPlanService;

    // @Log("查询InspectionPlan")
    @GetMapping(value = "/inspectionPlan")
    @PreAuthorize("hasAnyRole('ADMIN','INSPECTIONPLAN_ALL','INSPECTIONPLAN_SELECT')")
    public ResponseEntity getInspectionPlans(InspectionPlanQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(inspectionPlanService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("新增InspectionPlan")
    @PostMapping(value = "/inspectionPlan")
    @PreAuthorize("hasAnyRole('ADMIN','INSPECTIONPLAN_ALL','INSPECTIONPLAN_CREATE')")
    public ResponseEntity create(@Validated @RequestBody InspectionPlan resources){
        resources.setInputOperator(SecurityUtils.getName());
        resources.setInputTime(new Timestamp(System.currentTimeMillis()));
        return new ResponseEntity(inspectionPlanService.create(resources),HttpStatus.CREATED);
    }

    @Log("修改InspectionPlan")
    @PutMapping(value = "/inspectionPlan")
    @PreAuthorize("hasAnyRole('ADMIN','INSPECTIONPLAN_ALL','INSPECTIONPLAN_EDIT')")
    public ResponseEntity update(@Validated @RequestBody InspectionPlan resources){
        InspectionPlanDTO inspectionPlan = inspectionPlanService.findById(resources.getId());
        if(inspectionPlan==null) {
            return new ResponseEntity("巡检计划不存在", HttpStatus.BAD_REQUEST);
        }

        resources.setInputOperator(SecurityUtils.getName());
        resources.setInputTime(inspectionPlan.getInputTime());
        //TODO @@@@@ 任务调整

        inspectionPlanService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除InspectionPlan")
    @DeleteMapping(value = "/inspectionPlan/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','INSPECTIONPLAN_ALL','INSPECTIONPLAN_DELETE')")
    public ResponseEntity delete(@PathVariable Long id){
        inspectionPlanService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }
}